<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Wechat, User as Users, Business, Address, Region, Cart, Goods, GoodsSpec, Order, OrderGoods, Payment, Collect, PlatClass};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{
    public function login()
    {
        // Redis::setex(md5('123456'), 86400, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['unionid']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        //判断用户是否已经注册
        $user = $model->where('unionid', $res['unionid'])->find();
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $save = [
            'unionid' => $res['unionid'],
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            'avatarUrl' => $decryptedData['avatarUrl'] ?? '',
            'country' => $decryptedData['country'] ?? '',
            'nickName' =>  preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? ''),
        ];
        if ($user) {
            $res2 = (new Users())->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = (new Users())->allowfield(true)->save($save);
            $user = (new Users())->where('unionid', $res['unionid'])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }

        $this->result([], 1, '登录失败');
    }

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'gender' => $user['gender'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'intergal' => $user['intergal'],
            'collect' => (new Collect())->where(['user_id' => $this->request->user_id])->count(),
        ];
        $this->result($result, 0, '获取成功');
    }

    public function qrcode()
    {
        $name = 'appcode' . $this->request->user_id . '.png';
        $qcode = url('/uploads/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/wechat/";
        if (!file_exists($path . $name)) {
            $user = $this->request->user;
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $rm->save($path, $name);
            }
        }
        $this->result($qcode, 0, '获取成功');
    }

    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                'getaddress' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'province.require' => '省份不能为空',
                'city.require' => '城市不能为空',
                'area.require' => '区域不能为空',
                'address.require' => '具体地址不能为空',
                'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                'lat.require' => '经度不能为空',
                'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            if ($data['is_default'] == 2) {
                $addressmodel->where(['user_id' => $data['user_id'], 'is_default' => 2])->update(['is_default' => 1]);
            }
            if (!empty($data['id'])) {
                $res = $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $addressmodel->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $addressmodel = new Address();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            $this->result($result, 0, '操作成功');
        }
    }

    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function Collect()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require'
            ], [
                'goodsid.require' => '商品ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $goods = (new Goods())->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Collect())->where(['goodsid' => $data['goodsid'], 'user_id' => $this->request->user_id])->find();
            $save = [
                'user_id' => $this->request->user_id,
                'business' => $goods['businessid'],
                'goodsid' => $goods['id']
            ];
            if (!empty($mycart)) {
                $res =  (new Collect())->where('id', $mycart['id'])->delete();
            } else {
                $res =  (new Collect())->allowfield(true)->save($save);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $list = (new Collect())
                ->alias('c')
                ->distinct(true)
                ->join('goods g', 'g.id= c.goodsid')
                ->where(['c.user_id' => $this->request->user_id, 'g.isSale' => 1, 'g.isdel' => 1])
                ->field('g.id,g.title,g.images,g.descs')->paginate(20, false, ['query' => $this->request->param()]);;
            foreach ($list as $lists) {
                $lists['spec'] = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $lists['id']])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
                $lists['images'] = json_decode($lists['images'], true);
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function Collect_del()
    {
        $id = $this->request->post('id/d', '0');
        $cartmodel = new Collect();
        $result = $cartmodel->where(['user_id' => $this->request->user_id, 'goodsid' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    public function cart()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
                'number' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '商品规格不能为空',
                'number.require' => '商品数目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $goods = (new Goods())->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            $business = (new Business())->where(['id' => $goods['businessid'], 'status' => 1])->find();
            if (empty($business)) {
                $this->result([], 1, '商家已下架');
            }
            $goodsspec = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $goods['id'], 'id' => $data['specid']])->find();
            if (empty($goodsspec)) {
                $this->result([], 1, '规格产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['specid' => $data['specid'], 'user_id' => $this->request->user_id])->find();
            //购物车商品数量不能超过20个
            if (empty($mycart)) {
                $carts = (new Cart())->where(['user_id' => $this->request->user_id])->count();
                if ($carts >= 15) {
                    $this->result([], 1, '您的购物车产品数量已达到15个,请先结算或清空购物车');
                }
            }
            $number = (int)$data['number'] ?? 0;
            if (!empty($mycart)) {
                $number += $mycart['number'];
            }
            $save = [
                'user_id' => $this->request->user_id,
                'business' => $business['id'],
                'goodsid' => $goods['id'],
                'specid' => $goodsspec['id'],
                'number' => $number
            ];
            if (!empty($mycart)) {
                $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
            } else {
                $res =  (new Cart())->allowfield(true)->save($save);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $list = (new Cart())->where(['user_id' => $this->request->user_id])->select();
            $results = [];
            foreach ($list as $lists) {
                $info = (new Business())->field('id,title,sendkm,fwtime,city,area,address,lat,lon,zt,descs,mobile,sendmoney,sendm')
                    ->where(['id' => $lists['business']])->find();
                if (!empty($info)) {
                    $good = (new Goods())->where(['id' => $lists['goodsid']])->where(['isSale' => 1, 'isdel' => 1])->field('id,title,images')->find() ?? [];
                    $goodspec = (new GoodsSpec())->where('isdel', 1)->where(['id' => $lists['specid']])->field('name,price,unmit,stock')->find() ?? [];
                    if (empty($good) || empty($goodspec)) {
                        continue;
                    }
                    $goods = [];
                    $key = $lists['business'] ?? 0;
                    $results[$key]['info'] = $info;
                    $results[$key]['name'] = $info['title'];
                    $results[$key]['businessid'] = $info['id'];
                    $results[$key]['business'] = $lists['business'];
                    $goods = [
                        'cartid' => $lists['id'],
                        'goodsid' => $lists['goodsid'],
                        'specid' => $lists['specid'],
                        'title' => $good['title'] ?? '商品已下架',
                        'images' => json_decode($good['images'] ?? '', true) ?? [],
                        'spectitle' => $goodspec['name'] ?? '规格已下架',
                        'price' => $goodspec['price'] ?? 0,
                        'unmit' => $goodspec['unmit'] ?? '',
                        'number' => $lists['number']
                    ];
                    if (empty($results[$key]['total'])) {
                        $results[$key]['total'] = $goods['price'];
                    } else {
                        $results[$key]['total'] += $goods['price'];
                    }
                    $results[$key]['total'] = floor($results[$key]['total'] * 100) / 100;
                    $results[$key]['good'][] = $goods;
                }
            }
            $results = array_merge($results);
            $this->result($results, 0, '获取成功');
        }
    }

    public function cart_del()
    {
        $id = $this->request->post('id', '');
        $id = json_decode($id, true);
        if (count($id) <= 0) {
            $this->result([], 1, '操作失败');
        }
        $cartmodel = new Cart();
        $result = $cartmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'type' => 'require|in:1,2',
            'specid' => 'require',
            'addressid' => 'require'
        ], [
            'type.require' => '订单类型必须填写',
            'type.in' => '订单类型错误',
            'specid.require' => '规格ID不能为空',
            'addressid.require' => '地址ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true);
            if (empty($data['cartid'])) {
                $this->result([], 1, '购物车数据错误');
            }
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息错误存在');
        }
        $order = [
            'type' => $data['type'],
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'code' =>  orecode(new Order()),
            'businessid' => 0,
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'getaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'total' => 0,
            'remark' => $data['remark'] ?? '',
            'total' => 0,
            'ptotal' => 0
        ];
        $ordergoods = [];
        $sendmoney = 0; //起送金额
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新提交订单');
            }
            //判断商品是否下架
            $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            // if ($goodspec['stock'] < $spec['number']) {
            //     $this->result([], 1, '库存不足');
            // }
            //判断商户是否正常
            $business = (new Business())->where(['id' => $goods['businessid']])->find();
            if (empty($business) || $business['status'] != 1) {
                $this->result([], 1, '商家已下架');
            }
            if (empty($order['businessid'])) {
                $order['businessid'] = $goods['businessid'];
                if ($order['type'] == 1) {
                    $order['sendm'] = $business['sendm'];
                }
                $km = getDistance($address['lon'], $address['lat'], $business['lon'], $business['lat']);
                if ($km > $business['sendkm'] && $order['type'] == 1) {
                    $this->result([], 1, '超出商家配送距离');
                }
            } elseif ($order['businessid'] != $goods['businessid']) {
                $this->result([], 1, '不同门店商品不可同时下单');
            }
            $sendmoney = $business['sendmoney'];
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'businessid' => $goods['businessid'],
                'classid' => $goods['classid'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
        }
        $order['total'] = $order['ptotal'];
        if ($order['total'] < $sendmoney && $order['type'] == 1) {
            $this->result([], 1, '总价低于商家最低下单价格' . $sendmoney . '元，下单失败');
        }
        if ($order['type'] == 1) {
            $order['total'] += $order['sendm'];
        }
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        if ($order['total'] == 0) {
            $order['status'] = 2;
        }
        Db::startTrans();
        try {
            $id = (new Order())->insertGetId($order);
            (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where('id', $data['id'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1) {
                    $this->result([], 1, '订单不处于支付状态');
                }
                //支付订单 返回微信信息
                $ordersn = repayorder(new Payment());
                $wechatarr = [
                    'pay_title' => '订单支付',
                    'payment_id' =>  $ordersn,
                    'money' => $order['total'],
                    'ip' => $this->request->ip(),
                    'user_id' => $this->request->user_id,
                    'params' => json_encode(['trade_type' => 'JSAPI'], true)
                ];
                $list = (new Wechat())->pay($wechatarr);
                if ($list['status'] == true) {
                    //存储支付订单记录
                    $res = (new Payment())->save(['money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                    if ($res) {
                        $this->result($list, 0, '获取成功');
                    } else {
                        $this->result([], 1, '获取失败,请重试');
                    }
                } else {
                    $this->result([], 1, $list['msg'] ?? '获取失败');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'finishtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '5':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                if ($order['shouhou'] != 1) {
                    $this->result([], 1, '订单处于售后状态或已售后');
                }
                //未配送订单直接取消
                if ($order['status'] == 1 || $order['status'] == 2) {
                    $shouhou = 2;
                    $status = $data['status'];
                    $tuikuan = 2;
                    $msg = '取消成功';
                    if ($order['total'] > 0 && $order['status'] == 2) {
                        $msg = '取消成功,等待平台退款';
                    }
                    if ($order['status'] == 1) {
                        $shouhou = 1;
                        $tuikuan = 0;
                    }
                    if ($order['status'] == 2) {
                        $status = $order['status'];
                    }
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $data['id'])->update([
                            'status' => $status,
                            'text' => $data['text'] ?? '',
                            'shouhou' => $shouhou,
                            'tuikuan' => $tuikuan,
                            'caceltimes' => date('Y-m-d H:i:s')
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, $msg);
                }
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }


    public function orderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,ordersn,businessid,status,total,shouhou,tuikuan,type,created')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['business_name'] = (new Business())->where('id', $lists['businessid'])->value('title');
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
            foreach ($ordergoods as $goods) {
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('payment', true)->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['time'] = strtotime($list['created']) + 10 * 60 - time();
            $list['time'] = $list['time'] < 0 ? 0 : $list['time'];
            $list['business'] = (new Business())->where(['id' => $list['businessid']])->field('id,title,lon,lat,province,city,area,address,mobile')->find();
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function business()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $type  = $this->request->get('type/d', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Business())
            ->field('id,title,sendkm,fwtime,city,area,address,sendm,mobile,sendmoney,lat,lon,mobile,' . $filed)
            ->order('dist asc');
        if (!empty($type) && $type == 2) {
            $result = $result->where('zt', $type);
        }
        $result = $result->limit(1)->having('dist <= sendkm')
            ->select();
        $this->result($result, 0, '获取成功');
    }

    public function goods()
    {
        $data = $this->request->get();
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $business = (new Business())
            ->field('id,title,sendkm,' . $filed)
            ->order('dist asc')
            ->having('dist <= sendkm')
            ->select();
        //范围内商家ID
        $businessid = array_column($business->toArray(), 'id') ?? [];
        $result = (new Goods())->order('sale desc')->field('id,images,title,descs,businessid')->where(['businessid' => $businessid]);
        if (!empty($data['title'])) {
            $result = $result->where('title|keywords', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['recomm'])) {
            $result = $result->where('recomm', 2);
        }
        if (!empty($data['isnew'])) {
            $result = $result->where('isnew', 2);
        }
        $result = $result->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true);
            $results['spec'] = (new GoodsSpec())->where(['goodid' => $results['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
            $info = (new Business())->field('id,title,sendkm,fwtime,city,area,address,lat,lon,zt,descs,mobile,sendmoney,sendm')
                ->where(['id' => $results['businessid']])->find();
            $results['business'] = $info['title'] ?? '';
            $results['info'] = $info;
        }
        $this->result($result, 0, '获取成功');
    }

    public function getgoods()
    {
        $id  = $this->request->get('id/d', '0');
        $title  = $this->request->get('title');
        $lists = (new PlatClass())->where('isshow', 1)->order('sort desc')->field('id,name')->select();
        foreach ($lists as $k => $list) {
            $goods = (new Goods())
                ->where(['classid' => $list['id'], 'businessid' => $id, 'isSale' => 1, 'isdel' => 1]);
            if (!empty($title)) {
                $goods = $goods->where('title|keywords', 'like', '%' . $title . '%');
            }
            $goods = $goods->order(['id' => 'desc'])
                ->field('id,title,businessid,classid,images,descs')
                ->limit(100)
                ->select()->each(function ($good) {
                    $good['spec'] = (new GoodsSpec())->where(['goodid' => $good['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
                    $good['images'] = json_decode($good['images'], true);
                    return $good;
                });
            if (count($goods) == 0) {
                unset($lists[$k]);
            }
            $list['goods'] = $goods;
        }
        $lists = array_values($lists->toArray());
        $this->result($lists, 0, '获取成功');
    }

    public function getbusiness()
    {
        $id  = $this->request->get('id/d', '0');
        $lat  = $this->request->get('lat/f', 0);
        $lon  = $this->request->get('lon/f', 0);
        $result = (new Business())
            ->field('id,title,sendkm,fwtime,city,area,address,lat,lon,zt,descs,mobile,sendmoney,sendm')
            ->where('id', $id)
            ->find();
        if ($result) {
            $result['km'] = getDistance($lon, $lat, $result['lon'], $result['lat']);
        }
        $this->result($result, 0, '获取成功');
    }

    public function getgoodsdetail()
    {
        $id  = $this->request->get('id/d', '0');
        $result = (new Goods())->where(['id' => $id, 'isdel' => 1])->field('id,title,businessid,classid,images,sale,isSale,descs,goodsDesc')->find();
        if ($result) {
            $result['collect'] =  (new Collect())->where(['user_id' => $this->request->user_id, 'goodsid' => $result['id']])->count() > 0 ? 2 : 1;
            $result['images'] = json_decode($result['images'], true);
            $result['spec'] = (new GoodsSpec())->where(['goodid' => $result['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
            $result['business'] = (new Business())->where(['id' => $result['businessid']])->field('id,title,lon,lat,province,city,area,address,mobile')->find();
        }
        $this->result($result, 0, '获取成功');
    }
}
